package kibahead.chat;

import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import kibahed.interfaces.IServerClientConsumer;

public class Chatroom implements IServerClientConsumer {

	private static Map<Socket, ChatUser> users = new HashMap<Socket, ChatUser>();

	private String name;

	public Chatroom(String name) {
		this.name = name;
	}

	@Override
	public void doSpecificActions(Socket socket, String msg) {
		ChatUser user = users.get(socket);
		if (user != null) {
			StringBuffer buff = new StringBuffer();
			if (msg.startsWith("all/")) {
				buff.append(msg.replaceFirst("all/",
						String.format("*%s:", user.getName())));
				for (ChatUser u : users.values()) {
					if (u != user) {
						u.sendMessageToUser(buff.toString());
					}
				}
			} else if (msg.startsWith("name/")) {
				user.setName(msg.replaceFirst("name/", ""));
				user.sendMessageToUser(String.format("Name set to %s",
						user.getName()));
			} else if (msg.equals("?")) {
				buff.append("Type 'all/' to send a message to all users\n")
						.append("type 'username/' to send a message to this user\n")
						.append("type 'name/' to set yout username");
				user.sendMessageToUser(buff.toString());
			} else if (msg.matches(".*/.*")) {
				String target = msg.split("/")[0];
				buff.append(msg.replaceFirst(target+"/",
						String.format("%s:", user.getName())));
				for (ChatUser u : users.values()) {
					if (u.getName().equals(target)) {
						u.sendMessageToUser(buff.toString());
					}
				}
			}
		}

	}

	@Override
	public boolean isAlive() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void setSocket(Socket socket) {
		ChatUser user = new ChatUser(socket);
		users.put(socket, user);
		user.sendMessageToUser(String.format(
				"Welcome to chatroom %s\ntype ? for help", name));

	}

}
